package com.company.aicrawlers.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.company.aicrawlers.common.dto.PageResponse;
import com.company.aicrawlers.common.exception.BusinessException;
import com.company.aicrawlers.entity.Product;
import com.company.aicrawlers.mapper.ProductMapper;
import com.company.aicrawlers.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 产品服务实现类
 *
 * @author AI Crawlers Team
 * @date 2025-10-10
 */
@Slf4j
@Service
public class ProductServiceImpl implements ProductService {
    
    @Autowired
    private ProductMapper productMapper;
    
    @Override
    public PageResponse<Product> getPageList(Integer page, Integer size, String keyword, 
                                             String category, Integer isOurProduct, Integer status) {
        // 构建分页对象
        Page<Product> pageParam = new Page<>(page, size);
        
        // 构建查询条件
        LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.and(StrUtil.isNotBlank(keyword), wrapper -> 
                        wrapper.like(Product::getProductName, keyword)
                               .or()
                               .like(Product::getBrand, keyword))
                    .eq(StrUtil.isNotBlank(category), Product::getCategory, category)
                    .eq(isOurProduct != null, Product::getIsOurProduct, isOurProduct)
                    .eq(status != null, Product::getStatus, status)
                    .orderByDesc(Product::getCreateTime);
        
        // 执行分页查询
        IPage<Product> pageResult = productMapper.selectPage(pageParam, queryWrapper);
        
        // 封装返回结果
        return new PageResponse<>(
                pageResult.getTotal(),
                (int) pageResult.getCurrent(),
                (int) pageResult.getSize(),
                pageResult.getRecords()
        );
    }
    
    @Override
    public Product getById(Long productId) {
        Product product = productMapper.selectById(productId);
        if (product == null) {
            throw new BusinessException("产品不存在");
        }
        return product;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long create(Product product) {
        // 参数校验
        if (StrUtil.isBlank(product.getProductName())) {
            throw new BusinessException("产品名称不能为空");
        }
        
        // 检查产品名称是否重复
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Product::getProductName, product.getProductName())
               .eq(Product::getBrand, product.getBrand());
        Product exist = productMapper.selectOne(wrapper);
        
        if (exist != null) {
            throw new BusinessException("该产品已存在");
        }
        
        // 设置默认值
        if (product.getStatus() == null) {
            product.setStatus(1);
        }
        if (product.getIsOurProduct() == null) {
            product.setIsOurProduct(0);  // 默认为竞品
        }
        if (StrUtil.isBlank(product.getFocusLevel())) {
            product.setFocusLevel("normal");
        }
        if (StrUtil.isBlank(product.getProductStatus())) {
            product.setProductStatus("on_sale");
        }
        if (product.getSortOrder() == null) {
            product.setSortOrder(0);
        }
        
        product.setCreateTime(LocalDateTime.now());
        product.setUpdateTime(LocalDateTime.now());
        
        // 插入数据库
        productMapper.insert(product);
        
        log.info("创建产品成功，ID: {}, 名称: {}, 是否我方产品: {}", 
                product.getProductId(), product.getProductName(), product.getIsOurProduct());
        return product.getProductId();
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Product product) {
        // 检查产品是否存在
        Product existProduct = productMapper.selectById(product.getProductId());
        if (existProduct == null) {
            throw new BusinessException("产品不存在");
        }
        
        // 参数校验
        if (StrUtil.isBlank(product.getProductName())) {
            throw new BusinessException("产品名称不能为空");
        }
        
        // 检查名称是否与其他产品重复
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Product::getProductName, product.getProductName())
               .eq(StrUtil.isNotBlank(product.getBrand()), Product::getBrand, product.getBrand())
               .ne(Product::getProductId, product.getProductId());
        Product duplicate = productMapper.selectOne(wrapper);
        
        if (duplicate != null) {
            throw new BusinessException("该产品名称已存在");
        }
        
        product.setUpdateTime(LocalDateTime.now());
        
        // 更新数据库
        productMapper.updateById(product);
        
        log.info("更新产品成功，ID: {}", product.getProductId());
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long productId) {
        // 检查产品是否存在
        Product product = productMapper.selectById(productId);
        if (product == null) {
            throw new BusinessException("产品不存在");
        }
        
        // TODO: 检查是否被问句关联，如果被关联则不允许删除
        // 可以在后续添加这个校验
        
        // 删除产品
        productMapper.deleteById(productId);
        
        log.info("删除产品成功，ID: {}, 名称: {}", productId, product.getProductName());
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchDelete(List<Long> productIds) {
        if (productIds == null || productIds.isEmpty()) {
            throw new BusinessException("请选择要删除的产品");
        }
        
        // 批量删除
        productMapper.deleteBatchIds(productIds);
        
        log.info("批量删除产品成功，数量: {}", productIds.size());
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer batchImport(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            throw new BusinessException("请上传文件");
        }
        
        try (InputStream inputStream = file.getInputStream()) {
            // 读取Excel文件
            ExcelReader reader = ExcelUtil.getReader(inputStream);
            
            // 读取数据（跳过标题行）
            List<Map<String, Object>> rows = reader.readAll();
            
            if (rows.isEmpty()) {
                throw new BusinessException("文件中没有数据");
            }
            
            List<Product> products = new ArrayList<>();
            
            for (Map<String, Object> row : rows) {
                Product product = new Product();
                
                // 产品名称（必填）
                String name = row.get("产品名称") != null ? row.get("产品名称").toString() : null;
                if (StrUtil.isBlank(name)) {
                    continue; // 跳过空行
                }
                product.setProductName(name.trim());
                
                // 品牌
                String brand = row.get("品牌") != null ? row.get("品牌").toString() : null;
                product.setBrand(StrUtil.isNotBlank(brand) ? brand.trim() : null);
                
                // 型号
                String model = row.get("型号") != null ? row.get("型号").toString() : null;
                product.setModel(StrUtil.isNotBlank(model) ? model.trim() : null);
                
                // 产品类别
                String category = row.get("产品类别") != null ? row.get("产品类别").toString() : null;
                product.setCategory(StrUtil.isNotBlank(category) ? category.trim() : null);
                
                // 价格区间
                String priceRange = row.get("价格区间") != null ? row.get("价格区间").toString() : null;
                product.setPriceRange(StrUtil.isNotBlank(priceRange) ? priceRange.trim() : null);
                
                // 是否我方产品
                String isOur = row.get("是否我方产品") != null ? row.get("是否我方产品").toString() : "否";
                product.setIsOurProduct("是".equals(isOur.trim()) ? 1 : 0);
                
                // 关键词（逗号分隔）
                String keywordsStr = row.get("关键词") != null ? row.get("关键词").toString() : null;
                if (StrUtil.isNotBlank(keywordsStr)) {
                    List<String> keywords = Arrays.stream(keywordsStr.split("[,，]"))
                            .map(String::trim)
                            .filter(StrUtil::isNotBlank)
                            .collect(Collectors.toList());
                    product.setKeywords(keywords);
                }
                
                // 描述
                String desc = row.get("产品描述") != null ? row.get("产品描述").toString() : null;
                product.setDescription(StrUtil.isNotBlank(desc) ? desc.trim() : null);
                
                // 设置默认值
                product.setStatus(1);
                product.setFocusLevel("normal");
                product.setProductStatus("on_sale");
                product.setSortOrder(0);
                product.setCreateTime(LocalDateTime.now());
                product.setUpdateTime(LocalDateTime.now());
                
                products.add(product);
            }
            
            if (products.isEmpty()) {
                throw new BusinessException("没有有效的数据可导入");
            }
            
            // 批量插入
            products.forEach(productMapper::insert);
            
            log.info("批量导入产品成功，数量: {}", products.size());
            return products.size();
            
        } catch (Exception e) {
            log.error("批量导入产品失败", e);
            throw new BusinessException("批量导入失败：" + e.getMessage());
        }
    }
    
    @Override
    public List<String> getAllCategories() {
        LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(Product::getCategory)
                    .groupBy(Product::getCategory);
        
        List<Product> products = productMapper.selectList(queryWrapper);
        
        return products.stream()
                .map(Product::getCategory)
                .filter(StrUtil::isNotBlank)
                .distinct()
                .collect(Collectors.toList());
    }
    
    @Override
    public List<String> getAllBrands() {
        LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(Product::getBrand)
                    .groupBy(Product::getBrand);
        
        List<Product> products = productMapper.selectList(queryWrapper);
        
        return products.stream()
                .map(Product::getBrand)
                .filter(StrUtil::isNotBlank)
                .distinct()
                .collect(Collectors.toList());
    }
}

